from flask import Blueprint, render_template, jsonify, request
from models.entity.area import Area
import json
from utils.nodetree import get_all_area
from utils.result import result

mod = Blueprint("core_area", __name__, url_prefix="/core/area", template_folder="templates", static_folder="static")

# 获取区域的数据
@mod.route('/get_area/',methods=['GET','POST'])
def get_area():
    """
    {
    "parent_id" : 120000
    }
    """
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
        except:
            return result(success=0, error_code=-1, error_msg='数据格式错误')
        areas = Area.get_areas_by_parent_id(data['parent_id'])
        # print(province_id)
        tmp = {}
        data = []
        for item in areas:
            data.append({"id": item.area_id, "name": item.name, "parent_id": item.parent_id,
                         "level": item.level, "code": item.code, "wbs": item.wbs, "center": item.center,
                         "polyline": item.polyline})
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)

# 得到省得类目,通过level判断
@mod.route('/get_province/', methods=['GET', 'POST'])
def get_province():

    if request.method == 'POST' or 'GET':
        areas = Area.get_areas_by_level(1)
        tmp = {}
        data = []
        for item in areas:
            data.append({"id": item.area_id, "name": item.name, "parent_id": item.parent_id,
                         "level": item.level, "code": item.code, "wbs": item.wbs, "center": item.center,
                         "polyline": item.polyline})
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        return render_template('', **locals())

# 获取区县的数据
@mod.route('/get_county/',methods=['GET','POST'])
def get_county():
    # 得到区县
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
        except:
            return result(success=0, error_code=-1, error_msg='数据格式错误')
        city_id = dict['id']
        areas = Area.get_areas_by_parent_id(city_id)
        # print(province_id)
        tmp = {}
        data = []
        for item in areas:
            data.append({"id": item.area_id, "name": item.name, "parent_id": item.parent_id,
                         "level": item.level, "code": item.code, "wbs": item.wbs, "center": item.center,
                         "polyline": item.polyline})
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)

@mod.route('/get_town/',methods=['GET','POST'])
def get_town():
    if request.method == 'POST':
        try:
            data = json.loads(request.data.decode("utf-8"))
            print('data', data)
        except:
            return result(success=0, error_code=-1, error_msg='数据格式错误')
        county_id = dict['id']
        areas = Area.get_areas_by_parent_id(county_id)
        # print(province_id)
        tmp = {}
        data = []
        for item in areas:
            data.append({"id": item.area_id, "name": item.name, "parent_id": item.parent_id,
                         "level": item.level, "code": item.code, "wbs": item.wbs, "center": item.center,
                         "polyline": item.polyline})
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)

# 获取全国的地区
@mod.route('/get_area_all/',methods=['GET','POST'])
def get_area_all():
    # 得到省得类目
    if request.method == 'POST' or 'GET':
        areas = Area.get_area_all()
        tmp = {}
        data = []
        for item in areas:
            data.append({"id": item.area_id, "name": item.name, "parent_id": item.parent_id,
                         "level": item.level, "code": item.code, "wbs": item.wbs, "center": item.center,
                         "polyline": item.polyline})
        tmp['success'] = 1
        tmp['error_code'] = None
        tmp['error_msg'] = None
        tmp['data'] = data
        return jsonify(tmp)
    else:
        return render_template('', **locals())


@mod.route('/add/', methods=['GET', 'POST'])
def add_device():
    """增加区域"""
    """
    {
    "name":"ddddd10",
    "code":"d2ddd5",
    "area_id":"22222",
    "level":1
    "parent_id":3,
    "wsb":4,
    "center":4,
    "polyline":0,
    }
    """
    if request.method == 'POST':
        tmp = {}
        data = []
        dict = json.loads(request.data.decode("utf-8"))
        print('dict', dict)
        area = Area()
        try:
            area.from_dict(dict)
        except RuntimeError as e:
            return result(success=0,error_code=-1,error_msg=e)
        # if not DeviceType.get_device_type_by_id(dict['device_type_id']):
        #     return result(success=0,error_code=-2,error_msg='设备类型不存在')
        # if not DeviceGroup.get_device_group_by_id(dict['device_group_id']):
        #     return result(success=0,error_code=-2,error_msg='设备分组不存在')
        # if Device.get_device_by_name(dict['name']):
        #     return result(success=0,error_code=-2,error_msg='名称已经存在')
        # if Device.get_device_by_code(dict['code']):
        #     return result(success=0,error_code=-3,error_msg='设备编码已存在')
        # if device.save():
        #     # 建立分区和设备的中间表联系
        #     connectorA = DistrictWithDevice()
        #     connectorA.device_id = device.id
        #     connectorA.district_id = tmp['district_id']
        #     if connectorA.save() is False:
        #         print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        #         return result(success=0,error_code=-3,error_msg='未知错误')
        #
        #     return result(data=[device.to_dict()])
        else:
            return result(success=0,error_code=-4,error_msg="未知错误")
